'use strict';

const db = uniCloud.database()
const dbCmd = db.command
const diffTime = 8 * 60 * 60 * 1000;
// 获取指定的今天的时间戳
function getMsByDate(timeStr, dayStr) {
	return new Date(dayStr+' '+timeStr).getTime()-diffTime;
}
// 根据时间戳得到年月日
function getDateByMs(msTime) {
	let date = new Date(msTime+diffTime);
	return date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
}
exports.main = async (event, context) => {
	// 有湖北嫌疑
	if (event.questionB == '1' ||
		event.questionC == '1' ||
		event.questionD == '1' ||
		event.questionE == '1'
	) {
		// 有症状
		if (event.questionG == '1') {
			event.advice = 4;
		}
		// 无症状
		else {
			event.advice = 3;
		}
	}
	// 无湖北嫌疑
	else {
		// 乘坐外地公共交通工具
		if (event.questionF == '1') {
			// 发烧
			if (event.questionG == '1') {
				event.advice = 4;
			}
			// 无发烧
			else {
				event.advice = 3;
			}
		}
		// 无乘坐外地公共交通工具
		// 未出过本地区
		else if (event.questionA == '0') {
			// 发烧
			if (event.questionG == '1') {
				event.advice = 5;
			}
			// 无发烧
			else {
				event.advice = 1;
			}
		} else {
			// 发烧
			if (event.questionG == '1') {
				event.advice = 2;
			}
			// 无发烧
			else {
				event.advice = 1;
			}
		}
	}
	event.createTime = Date.now();
	let todayDate = getDateByMs(event.createTime);
	const collection = db.collection('company_collect');
	let todayStart = getMsByDate('00:00:00',todayDate);
	// 今日Ymd日期
	event.dayTime = todayStart;
	let todayEnd = getMsByDate('23:59:59',todayDate);
	let whereMap = {
		'jobnumber': event.jobnumber,
		'company': event.company,
		'createTime': dbCmd.gte(todayStart).and(dbCmd.lte(todayEnd))
	};
	// 查询当天是否存在数据
	const userRes = await collection.where(whereMap).get();
	if (userRes.data.length > 0) {
		await collection.doc(userRes.data[0]._id).update(event);
	} else {
		await collection.add(event);
	}
	return event.advice;
};
